<?php
Yii::import('ext.widgets.ELike.LikeData');
class LikeAction extends Action {
    
    public $module;
    public $moduleId;
    
    public function run(){
        $this->loginRequired();
        $params=LikeData::getData($this->module);
        if(isset($params[$this->moduleId]) && ($params[$this->moduleId] == Option::STATUS_ACTIVE)){
            $result = 0;
            $total = $this->removeItem();
        }else{
            $result = 1; 
            $total = $this->addItem();
        }

        if (Yii::app()->request->isAjaxRequest || isset($_GET['ajax'])){
            echo CJSON::encode(array(
                'status'=>'success',
                'result'=>$result,
                'total'=>$total,
            ));
        } else {
            $this->controller->redirect(Yii::app()->request->urlReferrer);
        }
    }
    
    public function addItem(){
        $model = new Like;
        $model->module_ = $this->module;
        $model->moduleId_ = $this->moduleId;
        if ($model->addRecord()) {
            LikeData::add($this->module, $this->moduleId);
            $total='';
            $d = $this->module;
            $data = $d::model()->published()->findByPk($this->moduleId);
            if (!empty($data)){
                $data->updateLikeCounter();
                $data->refresh();
                //$this->sendNotification($model, $data);
                $total=$data->totalLike;
            }
            return $total;
        }else{
            return $model->getErrors();
        }
    }
    
    public function removeItem(){
        $data=Like::model()->module($this->module)->moduleId($this->moduleId)->userId(Yii::app()->user->id)->accessible()->find();
        if (empty($data))
            HttpStatus::code(404);
        if ($data->deleteRecord()) {
            LikeData::delete($this->module, $this->moduleId);
            $d = $this->module;
            $data = $d::model()->published()->findByPk($this->moduleId);
            if (!empty($data)){
                $data->updateLikeCounter(-1);
                $data->refresh();
                $total=$data->totalLike;
            }
            return $total;
        }
    }
    
    public function sendNotification(&$like, &$data){
        
    }
    
}